package test.ground.netty.netty.my;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 客户端的长时间没写,就写一个心跳过去
 */
public class ClientHeartBeatHandler extends ChannelInboundHandlerAdapter{

    //当超过n秒没有写时会触发该事件
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.WRITER_IDLE) {
                ctx.writeAndFlush(new Message());
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}